package com.dodo.controller.user;

import com.dodo.dto.GoodsSalesDTO;
import com.dodo.dto.RankDTO;
import com.dodo.mapper.OrderMapper;
import com.dodo.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@RestController
@RequestMapping("/user/rank")
@Api(tags = "C端排行榜相关接口")
@Slf4j
public class RankController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @GetMapping("/list")
    @ApiOperation("用户销量排行榜")
    public Result<List<GoodsSalesDTO>> rankList(){
        log.info("用户销量排行榜");

        List<GoodsSalesDTO> rankDTOS = (List<GoodsSalesDTO>)redisTemplate.opsForValue().get("rank");
        if (rankDTOS != null && rankDTOS.size() > 0 ){
            return Result.success(rankDTOS);
        }

        LocalDate yesterday = LocalDate.now();

        LocalDateTime begin = LocalDateTime.of(yesterday, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(yesterday, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(begin, end);

        redisTemplate.opsForValue().set("rank", salesTop10);
        return Result.success(rankDTOS);
    }

}
